import { _decorator, Component, Node, input, Input, __private, EventTouch, v3, UITransform, view, Size, Prefab, instantiate, Collider2D, Contact2DType, find, Animation, Label, director, Director } from 'cc';
import { BulletConstant } from './constant/BulletConstant';
import { SysContant } from './constant/SysContant';
import { EnemyFactory } from './EnemyFactory';
import { HeroLifeMgr } from './HeroLifeMgr';
import { AudioMgr } from './tool/AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('HeroControl')
export class HeroControl extends Component {
    
    nodeUI: UITransform;
    viewSize: Size;
    

    @property(Prefab)
    bulletPrefab:Prefab[] = []

    @property(Node)
    battaleNode:Node
    heroLifeMgr: Node;


    // 英雄是霸体
    bati: boolean = false;

    
    start() {

        this.nodeUI = this.node.getComponent(UITransform)
        this.viewSize = view.getVisibleSize()

        this.heroLifeMgr = find('Canvas/control/heroLife/life')

        let collider = this.node.getComponent(Collider2D)
        if(collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
        }

        
    }
    
    
    update(deltaTime: number) {
        
    }

    startGame() {

        input.on(Input.EventType.TOUCH_MOVE, this.heroFly, this)

        this.shotSchedule()

    }

    gameOver() {
        input.off(Input.EventType.TOUCH_MOVE, this.heroFly, this)
        this.unschedule(this.shot)
    }
    
    
    
    // 移动英雄
    heroFly(event: EventTouch) {


        // console.log('getPosition', this.node.getPosition())
        // console.log('getWorldPosition', this.node.getWorldPosition())

        
        // 移动位置
        let delta = event.getDelta()

        // hero
        let curPos = this.node.getWorldPosition()

        // 目标位置
        let {x , y} = curPos.add(v3(delta.x, delta.y))

        let halfW = this.nodeUI.width / 2
        let halfH = this.nodeUI.height / 2

        // x
        if(x < halfW) {
            x = halfW
        }else if( x > this.viewSize.width - halfW) {
            x = this.viewSize.width - halfW
        }
        
        if(y < halfH) {
            y = halfH
        }else if( y > this.viewSize.height - halfH) {
            y = this.viewSize.height - halfH
        }


        // 赋值
        this.node.setWorldPosition(v3(x , y))

    }


    shotSchedule() {
        this.schedule(this.shot, BulletConstant.bulletAttrs[0].freq)
    }
    shot() {
        let bulletIndex = SysContant.bulletIndex
        
        let {x, y} = this.node.position
        
        if(bulletIndex) {
            
            let bullet = instantiate(this.bulletPrefab[bulletIndex])
            let bullet1 = instantiate(this.bulletPrefab[bulletIndex])

            bullet.setPosition(v3(x-15, y + this.nodeUI.height / 2))
            bullet1.setPosition(v3(x+15, y + this.nodeUI.height / 2))

            bullet.setParent(this.battaleNode)
            bullet1.setParent(this.battaleNode)

        }else {
            let bullet = instantiate(this.bulletPrefab[bulletIndex])
    
            bullet.setPosition(v3(x, y + this.nodeUI.height / 2))
    
            bullet.setParent(this.battaleNode)
        }

    }


    
    die() {
        /**
         * 
         * 1. 减少生命
         * 2. 播放死亡动画和声音
         * 3. 没生命了消失 ==> gameover
         * 
         */

        // 1.
        SysContant.inst.reduceHeroLife(1)
        this.heroLifeMgr.getComponent(HeroLifeMgr).showHeroLife()

        // 2.
        this.node.getComponent(Animation).play('hero_die')
        AudioMgr.inst.playOneShot('sound/me_down')
        this.bati = true

        // 3. 如果没有生命了, 则消亡, 如果还有, 则切换到默认动画
        if(SysContant.inst.heroLife <= 0) {
            // 死亡
            this.scheduleOnce(() => {
                this.bati = false
                this.node.active = false
                this.node.getComponent(Animation).play()
            }, 1)

            // 游戏结束
            // 设置分数, 显示结束游戏面板
            find('Canvas/gameover/score').getComponent(Label).string = SysContant.inst.gameScore + ''
            find('Canvas/gameover').active = true

        }else {
            // 继续游戏
            this.scheduleOnce(() => {
                this.bati = false
                this.node.getComponent(Animation).play()
            }, 1)
        }



    }


    // 获得超级子弹时间
    setSuperBulletTime() {
        
        if(SysContant.bulletIndex == 1) {
            // 已经是超级子弹了,  重新计时
            this.unschedule(this.setBullet0)
        }

        SysContant.bulletIndex = 1

        this.scheduleOnce(this.setBullet0, BulletConstant.superTime)
    }
    setBullet0() {
        SysContant.bulletIndex = 0
    }
    // 炸弹效果
    killAllEnemys() {
        find('Canvas/enemys').getComponent(EnemyFactory).killAllEnemys()
    }

    // 碰撞回调
    onBeginContact(self: Collider2D, other: Collider2D) {
        let hero = self.getComponent(HeroControl)
        if(!hero.bati && self.tag == 0 && other.tag == 2) {
            // 英雄死亡
            hero.die()
        }

        // 子弹或炸弹
        if(!hero.bati && self.tag == 0 && other.tag == 3) {
            // 获得超级子弹时间
            hero.setSuperBulletTime()
            
            // 移除buf
            director.once(Director.EVENT_AFTER_PHYSICS, ()=> {
                other.node.destroy()
            })
        }
        
        // 子弹或炸弹
        if(!hero.bati && self.tag == 0 && other.tag == 4) {
            // 获得一个炸弹  所有敌机爆炸并加分
            hero.killAllEnemys()
            
            // 移除buf
            director.once(Director.EVENT_AFTER_PHYSICS, ()=> {
                other.node.destroy()
            })
        }
    }
}


